<template>
  <div class="sub-form-wrapper">
    <a-card :title="field.label || '全部'">
      <RenderFormFieldList
        v-if="field.genConfig.subFormType === 'singleRow'"
        :layout-config="layoutConfig"
        :field="field"
        @selectField="handleSelectCol"
      />
      <a-table
        v-else
        ref="tableRef"
        :dataSource="dataSource"
        :columns="columns"
        style="width: 100%"
        border
      >
        <template #headerCell="{ column }">
          <div style="cursor: pointer" @click="handleSelectCol(column)">
            {{ column.formKey === "action" ? "操作" : column.label }}
          </div>
        </template>
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.label === '操作'">
            <a> 删除 </a>
          </template>
          <template v-else-if="column.label === '序号'">
            <span>
              {{ index + 1 }}
            </span>
          </template>
          <template v-else>
            <field-renderer
              isPreview
              :showLabel="false"
              :formLayout="layoutConfig.formLayout"
              :field="column"
              :formData="record"
              v-model:value="record[column.formKey]"
            />
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { computed } from "vue";
import FieldRenderer from "./FieldRenderer.vue";
import RenderFormFieldList from "./RenderFormFieldList.vue";

const props = defineProps({
  layoutConfig: { type: Object, default: () => ({}) },
  field: { type: Object, default: () => ({}) },
});
const emits = defineEmits(["selectField", "click"]);

const dataSource = computed(() => {
  const dataItem = {};
  props.field.fieldList.forEach((item) => {
    dataItem[item.formKey] = "";
  });
  return [dataItem, { ...dataItem }];
});

const columns = computed(() => {
  return field.fieldList.map((item) => ({
    title: item.label,
    dataIndex: item.formKey,
    key: item.formKey,
  }));
});

function handleSelectCol(record) {
  emits("selectField", record);
}
function handleClick() {
  console.log("🚀 ~ handleClick ~ handleClick:");
  emits("click", props.handleClick);
}
</script>

<style scoped lang="less">
.sub-form-wrapper {
  ::v-deep {
    .el-card__body {
      padding: 10px;
    }
    .el-table .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
